#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2016 lizongzhe 
#
# Distributed under terms of the MIT license.
import requests
from proxy_manager.exceptions import ProxyCheckError
import logging
import urllib

logger = logging.getLogger(__name__)

class BaseProxyChecker(object):
    base_callbacks = []
    def __init__(self, callback):
        self.callback = callback
        

    def __call__(self, proxy_host):
        try:
            self.callback(proxy_host)
        except Exception as e:
            raise ProxyCheckError()

        
class PortChecker(BaseProxyChecker):
    def __init__(self, ports):
        if isinstance(ports, basestring):
            ports = int(ports)
        if isinstance(ports, int):
            ports = [ports]
        self.ports = ports
        self.callback = self.check

    def check(self, proxy_host):
        assert int(proxy_host.port) in self.ports

class SchemeChecker(BaseProxyChecker):
    def __init__(self, schemes):
        if isinstance(schemes, basestring):
            schemes = [schemes]

        self.schemes = schemes
        self.callback = self.check

    def __unicode__(self):
        return '{}:{}'.format('SchemeChecker', self.schemes)

    def check(self, proxy_host):
        assert proxy_host.scheme in self.schemes


class ProxyChecker(BaseProxyChecker):
    def __init__(self, url, method='get', headers={}, data={}, timeout=5, response_check_callback=None):
        self.url = url.strip()
        self.headers = headers
        self.data = data
        self.timeout=timeout
        method = method.lower()
        self.method=method

        self.callback = self.check
        self.response_check_callback = response_check_callback


    def get(self, proxy_host):
        query = urllib.urlencode(self.data)
        url = self.url
        if "?" in url:
            if not url.endswith('&'):
                url += "&"
        else:
            url += "?"

        url += query
        return requests.get(url, headers=self.headers, timeout=self.timeout, proxies={proxy_host.scheme: proxy_host.ip})

    def post(self, proxy_host):
        return requests.post(self.url, data=self.data, headers=self.headers, timeout=self.timeout, proxies={proxy_host.scheme: proxy_host.ip})

    def check(self, proxy_host):       
        logger.info(proxy_host)
        response = getattr(self, self.method)(proxy_host)
        if self.response_check_callback:
            self.response_check_callback(response)

